package yc.bluetooth.ycvoiceprotest.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

import yc.bluetooth.ycvoiceprotest.R;
import yc.bluetooth.ycvoiceprotest.data.BDevice;


public class LVDevicesAdapter extends BaseAdapter {

    private Context context;
    private List<BDevice> list;

    public LVDevicesAdapter(Context context, List<BDevice> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list == null ?  0 : list.size();
    }

    @Override
    public Object getItem(int i) {
        if(list == null){
            return null;
        }
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        DeviceViewHolder viewHolder;
        if(view == null){
            view = LayoutInflater.from(context).inflate(R.layout.layout_lv_devices_item,null);
            viewHolder = new DeviceViewHolder();
            viewHolder.tvDeviceName = view.findViewById(R.id.tv_device_name);
            viewHolder.tvDeviceAddress = view.findViewById(R.id.tv_device_address);
            viewHolder.tvDeviceRssi = view.findViewById(R.id.tv_device_rssi);
            view.setTag(viewHolder);
        }else{
            viewHolder = (DeviceViewHolder) view.getTag();
        }

        if(list.get(i).bluetoothDevice.getName() == null){
            viewHolder.tvDeviceName.setText("NULL");
        }else{
            viewHolder.tvDeviceName.setText(list.get(i).bluetoothDevice.getName());
        }

        viewHolder.tvDeviceAddress.setText(list.get(i).bluetoothDevice.getAddress());
        viewHolder.tvDeviceRssi.setText("RSSI：" + list.get(i).rssi);

        return view;
    }

    /**
     * 添加列表子项
     * @param bDevice
     */
    public void addDevice(BDevice bDevice){
        if(list == null){
            return;
        }
        if(!list.contains(bDevice)){
            list.add(bDevice);
        }
        notifyDataSetChanged();   //刷新
    }

    /**
     * 清空列表
     */
    public void clear(){
        if(list != null){
            list.clear();
        }
        notifyDataSetChanged(); //刷新
    }

    class DeviceViewHolder {

        TextView tvDeviceName;
        TextView tvDeviceAddress;
        TextView tvDeviceRssi;
    }

}
